import { useCallback, useEffect, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Stack, useRouter } from 'expo-router';

import { PageHeader } from '@/components/page-header';
import { FavoriteItem, getFavorites } from '@/utils/favorites';
import { fetchProductThumbnail, ProductThumbnail } from '@/utils/product-thumb';
import { CircleThumbnail } from '@/components/circle-thumbnail';

const palette = {
  background: '#fdf7fb',
  surface: '#ffffff',
  border: 'rgba(214, 106, 138, 0.18)',
  textPrimary: '#2f1f2b',
  textHint: '#9c8aa0',
};

type FavoriteDisplay = FavoriteItem & {
  imageUrl: string | null;
  productTitle: string;
  price: number | null;
};

export default function FavoritesScreen() {
  const router = useRouter();
  const [items, setItems] = useState<FavoriteDisplay[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const loadFavorites = useCallback(async () => {
    const data = await getFavorites();
    const enriched = await Promise.all(
      data.map(async (item): Promise<FavoriteDisplay> => {
        try {
          const thumbnail: ProductThumbnail = await fetchProductThumbnail(item.id);
          return {
            ...item,
            productTitle: thumbnail.title || item.title,
            imageUrl: thumbnail.imageUrl,
            price: thumbnail.price,
          };
        } catch {
          return {
            ...item,
            productTitle: item.title,
            imageUrl: null,
            price: null,
          };
        }
      }),
    );
    setItems(enriched);
  }, []);

  useEffect(() => {
    loadFavorites();
  }, [loadFavorites]);

  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadFavorites();
    setRefreshing(false);
  }, [loadFavorites]);

  const formatDate = (value: string) => {
    const d = new Date(value);
    return Number.isNaN(d.getTime())
      ? value
      : d.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
        });
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <Stack.Screen options={{ title: '收藏 / 喜欢' }} />
      <PageHeader title="收藏 / 喜欢" />
      <ScrollView
        contentContainerStyle={styles.container}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}
      >
        <View style={styles.card}>
          {items.map((it) => (
            <Pressable
              key={it.id}
              style={styles.row}
              onPress={() => router.push({ pathname: '/c/product/[id]', params: { id: String(it.id) } })}
            >
              <CircleThumbnail uri={it.imageUrl} size={56} />
              <View style={styles.rowContent}>
                <Text style={styles.title}>{it.productTitle}</Text>
                <Text style={styles.meta}>收藏时间：{formatDate(it.markedAt)}</Text>
              </View>
              {typeof it.price === 'number' ? (
                <Text style={styles.price}>¥{it.price.toFixed(2)}</Text>
              ) : null}
            </Pressable>
          ))}
          {items.length === 0 ? (
            <View style={styles.emptyBox}>
              <Text style={styles.emptyText}>还没有收藏的商品</Text>
            </View>
          ) : null}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: palette.background },
  container: { padding: 16, gap: 16 },
  card: {
    borderRadius: 24,
    backgroundColor: palette.surface,
    padding: 12,
    borderWidth: 1,
    borderColor: palette.border,
    gap: 12,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 14,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#eee',
  },
  rowContent: {
    flex: 1,
  },
  title: { fontSize: 15, fontWeight: '600', color: palette.textPrimary },
  meta: { marginTop: 4, fontSize: 12, color: palette.textHint },
  price: { fontSize: 14, fontWeight: '600', color: palette.textPrimary },
  emptyBox: { alignItems: 'center', paddingVertical: 20 },
  emptyText: { fontSize: 13, color: palette.textHint },
});

